import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@WebServlet("/postjson")
public class JsonPostServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //返回类型和编码
        resp.setContentType("text/html;charset=utf-8");
        //1.得到数据流
        ServletInputStream inputStream=req.getInputStream();
        //2.使用数组接收流信息
        byte[] bytes=new byte[req.getContentLength()];
        inputStream.read(bytes);
        //3.将数组转换成字符串（或对象）
        String result=new String(bytes,"utf-8");
        System.out.println(result);
        ObjectMapper objectMapper=new ObjectMapper();
        HashMap<String,String > map=objectMapper.readValue(result,HashMap.class);
        System.out.println("用户名："+map.get("username"));
        System.out.println("密码："+map.get("password"));
        resp.getWriter().println("用户名："+map.get("username")+"密码："+map.get("password"));
//        String username=req.getParameter("username");
//        String password=req.getParameter("password");
//        System.out.println("username:"+username);
//        System.out.println("password:"+password);
//        resp.getWriter().write("username"+username);
    }
}
